#ifndef DEVICESEARCHWIDGET_H
#define DEVICESEARCHWIDGET_H

#include <QWidget>
#include <QTableWidgetItem>
#include <QProgressBar>
#include <QLabel>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDialog>
#include <QLineEdit>
#include <QCheckBox>
#include <QComboBox>
#include <QCryptographicHash>
#include <QUuid>
#include <QNetworkInterface>
#include "../core/device/devicemanager.h"
#include "../core/discovery/discoveryclient.h"
#include "../media/ffmpeg/ffmpeg.h"
#include "firmwareupgradedialog.h"

QT_BEGIN_NAMESPACE
namespace Ui { class DeviceSearchWidget; }
QT_END_NAMESPACE

class LoginDialog : public QDialog
{
    Q_OBJECT

public:
    explicit LoginDialog(const QString &deviceAddress, QWidget *parent = nullptr);
    
    QString getUsername() const;
    QString getPassword() const;
    bool getRememberMe() const;

private:
    QLineEdit *m_usernameEdit;
    QLineEdit *m_passwordEdit;
    QCheckBox *m_rememberMeCheckBox;
};

class NetworkConfigDialog : public QDialog
{
    Q_OBJECT

public:
    explicit NetworkConfigDialog(QWidget *parent = nullptr);
    
    void setNetworkConfig(const QJsonObject &config);
    
signals:
    void networkConfigRequested();
    void setNetworkConfigRequested(const QString &interfaceName, bool enable, const QString &mode,
                                  const QString &ipAddress, const QString &netmask, const QString &gateway);

private slots:
    void onModeChanged();
    void onGetConfigClicked();
    void onSetConfigClicked();

private:
    QComboBox *m_interfaceCombo;
    QCheckBox *m_enableCheckBox;
    QComboBox *m_modeCombo;
    QLineEdit *m_ipAddressEdit;
    QLineEdit *m_netmaskEdit;
    QLineEdit *m_gatewayEdit;
    QLabel *m_statusLabel;
    QPushButton *m_getConfigBtn;
    QPushButton *m_setConfigBtn;
    QWidget *m_staticConfigWidget;
};

struct DeviceInfo {
    QString ipAddress;
    int port;
    QString deviceType;
    QString manufacturer;
    QString model;
    QString status;
    QString webInterface;
    QString rtspUrl;
    QJsonObject additionalInfo;
    
    // 生成指定通道和码流类型的RTSP URL
    // channel: 通道号 (1, 2, 3...)
    // streamType: 0=主码流, 1=子码流
    QString getRtspUrl(int channel = 1, int streamType = 0) const {
        return QString("rtsp://%1:554/live/%2/%3").arg(ipAddress).arg(channel).arg(streamType);
    }
    
    // 获取主码流URL (通道1)
    QString getMainStreamUrl(int channel = 1) const {
        return getRtspUrl(channel, 0);
    }
    
    // 获取子码流URL (通道1) 
    QString getSubStreamUrl(int channel = 1) const {
        return getRtspUrl(channel, 1);
    }
};

class DeviceSearchWidget : public QWidget
{
    Q_OBJECT

public:
    DeviceSearchWidget(QWidget *parent = nullptr);
    ~DeviceSearchWidget();

private slots:
    void on_btnSearch_clicked();
    void on_btnStop_clicked();
    void on_btnRefresh_clicked();
    void on_btnExport_clicked();
    void on_btnConnect_clicked();
    void on_btnViewStream_clicked();
    void on_btnWebInterface_clicked();
    void on_btnModifyParams_clicked();
    void on_btnUpgrade_clicked();
    void on_tblDevices_itemSelectionChanged();
    
    void onDeviceFound(const DeviceInfo &device);
    void onDiscoveryDeviceFound(const Discovery::DeviceDiscoveryInfo &device);
    void onDiscoveryFinished();
    void onDiscoveryError(const QString &error);
    
    // 设备管理相关槽函数
    void onDeviceConnectionStateChanged(const QString &ipAddress, bool connected);
    void onDeviceError(const QString &ipAddress, const QString &errorMessage);
    void onChallengeReceived(const QString &ipAddress, const QString &challenge, int expiresIn);
    void onLoginSuccess(const QString &ipAddress, const QString &accessToken, const QString &refreshToken, const QJsonObject &userInfo);
    void onLoginFailed(const QString &ipAddress, int errorCode, const QString &errorMessage);
    
    // 网络配置相关槽函数
    void onNetworkConfigReceived(const QString &ipAddress, const QJsonObject &config);
    void onNetworkConfigSetResult(const QString &ipAddress, bool success, const QString &message);

private:
    void setupUI();
    void updateDeviceDetails(const DeviceInfo &device);
    void updateDeviceCount();
    void setSearchEnabled(bool enabled);
    void addDeviceToTable(const DeviceInfo &device);
    QString formatDeviceDetails(const DeviceInfo &device);
    
    // 网络接口管理
    void loadNetworkInterfaces();
    QString getSelectedNetworkInterface() const;
    
    // 登录相关辅助方法
    QString generateCredential(const QString &password, const QString &challenge);
    void connectToDeviceWithLogin(const DeviceInfo &device);
    
    Ui::DeviceSearchWidget *ui;
    QList<DeviceInfo> m_foundDevices;
    DeviceManager *m_deviceManager;
    Discovery::DiscoveryClient *m_discoveryClient;
    int m_discoveryCallbackHandle;
    
    // 登录相关变量
    QString m_deviceId;           // 设备ID
    QString m_currentUsername;    // 当前登录用户名
    QString m_currentPassword;    // 当前登录密码（临时存储）
    bool m_rememberMe;            // 是否记住密码
    DeviceInfo m_connectingDevice; // 正在连接的设备信息
    NetworkConfigDialog *m_networkConfigDialog; // 网络配置对话框
    FirmwareUpgradeDialog *m_firmwareUpgradeDialog; // 固件升级对话框

    // 搜索进度相关
    QTimer *m_progressTimer {nullptr};
    QElapsedTimer m_searchElapsedTimer;
    int m_searchTimeoutSeconds {0};
};

#endif // DEVICESEARCHWIDGET_H